<template>
  <el-card shadow="hover">
    <el-form inline :disabled="disabled">
      <el-form-item label="一级分类">
        <el-select
          placeholder="请选择一级分类"
          v-model="categoryStore.category1Id"
        >
          <!-- 
            label 用来展示的
            value 选中得到的值
           -->
          <el-option
            v-for="c1 in categoryStore.category1List"
            :key="c1.id"
            :label="c1.name"
            :value="c1.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select
          placeholder="请选择二级分类"
          v-model="categoryStore.category2Id"
        >
          <el-option
            v-for="c2 in categoryStore.category2List"
            :key="c2.id"
            :label="c2.name"
            :value="c2.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select
          placeholder="请选择三级分类"
          v-model="categoryStore.category3Id"
        >
          <el-option
            v-for="c3 in categoryStore.category3List"
            :key="c3.id"
            :label="c3.name"
            :value="c3.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { onMounted, watch } from "vue";
import { useCategoryStore } from "@/stores/category";

defineOptions({
  name: "CategorySelector",
});

defineProps<{
  disabled: boolean;
}>();

const categoryStore = useCategoryStore();

// 1. 一上来获取一级分类列表
onMounted(() => {
  categoryStore.getCategory1List();
});

// 2. 监视一级分类id变化，请求二级分类列表数据
watch(
  () => categoryStore.category1Id,
  () => {
    categoryStore.getCategory2List();
  }
);

// 3. 监视二级分类id变化，请求三级分类列表数据
watch(
  () => categoryStore.category2Id,
  (category2Id) => {
    if (!category2Id) return;
    categoryStore.getCategory3List();
  }
);
</script>

<style scoped lang="scss">
// scoped 会影响子组件的根标签
// el-form-item 就是子组件根标签的类名
.el-form-item {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
